import nltk
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB

def text_dispose(text):
    # 将每个单词和符号分开，处理邮件内容
    sentences = nltk.sent_tokenize(text)
    words = [word for sent in sentences for word in nltk.word_tokenize(sent)]
    stops = stopwords.words('english') # 加载停用词
    # 去除停用词
    words = [word for word in words if words not in stops]
    words = [words.lower() for words in words if len(words) >= 3]
    # 词汇化
    lemmatizer = WordNetLemmatizer()
    words = [lemmatizer.lemmatize(words) for words in words]
    dispose_text = ' '.join(words)
    return dispose_text

sms_data = open('data/SMSSpamCollection', 'r', encoding='UTF-8')
x = []
y = []
for line in sms_data.readlines():
    data = line.split('\t')
    y.append(data[0])
    x.append(text_dispose(data[1].split('\n')[0]))
sms_data.close()

# 拆分
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=1)
# 特征处理
vectorizer = TfidfVectorizer(min_df=2, ngram_range=(1, 2), stop_words='english', strip_accents='unicode', norm='l2')
X_train = vectorizer.fit_transform(x_train)
X_test = vectorizer.transform(x_test)

model = MultinomialNB()
model.fit(X_train,y_train)

y_predict = model.predict(X_test)
score = model.score(X_test, y_test)
print(score)


